"""
高级EventBus与HookHub桥接器示例
展示异步事件处理和复杂集成场景
"""

import asyncio
import threading
import time
from typing import Any, Dict, Optional, Tuple
from event_bus_bridge import EventBusBridge
from hook_hub import HookHub


class AdvancedEventProcessor:
    """高级事件处理器"""
    
    def __init__(self, hook_hub: HookHub) -> None:
        self.hook_hub = hook_hub
        self.processed_count = 0
        
    def sync_event_handler(self, **kwargs) -> None:
        """同步事件处理器"""
        payload = kwargs.get('payload', 'unknown')
        self.processed_count += 1
        print(f"[Sync] 处理事件 #{self.processed_count}: {payload}")
        
    async def async_event_handler(self, **kwargs) -> str:
        """异步事件处理器"""
        payload = kwargs.get('payload', 'unknown')
        # 模拟异步处理
        await asyncio.sleep(0.1)
        result = f"异步处理结果: {payload}"
        print(f"[Async] {result}")
        return result
        
    def error_handler(self, **kwargs) -> bool:
        """错误处理示例，返回False停止事件传播"""
        payload = kwargs.get('payload', 'unknown')
        if "error" in payload.lower():
            print(f"[Error] 检测到错误事件: {payload}")
            return False  # 停止传播
        return True


def setup_event_processing() -> Tuple[EventBusBridge, AdvancedEventProcessor]:
    """设置事件处理系统"""
    # 创建HookHub实例
    hook_hub = HookHub()
    
    # 创建高级事件处理器
    processor = AdvancedEventProcessor(hook_hub)
    
    # 创建桥接器，使用事件ID到事件名称的映射
    event_mapping = {
        0xC0: "data_event",
        0xC1: "data_event",
        0xC2: "log_event"
    }
    bridge = EventBusBridge(hook_hub, event_id_mapping=event_mapping)
    
    # 注册各种事件处理器
    hook_hub.register("data_event", processor.sync_event_handler, priority=10)
    hook_hub.register("data_event", processor.async_event_handler, priority=5, is_async=True)
    hook_hub.register("data_event", processor.error_handler, priority=1)
    
    # 注册日志事件处理器
    def log_handler(**kwargs):
        payload = kwargs.get('payload', 'unknown')
        print(f"[Log] 日志事件: {payload}")
    
    hook_hub.register("log_event", log_handler, priority=2)
    
    return bridge, processor


async def async_main():
    """异步主函数"""
    print("=== 高级EventBus与HookHub桥接器示例 ===")
    
    # 设置事件处理系统
    bridge, processor = setup_event_processing()
    
    # 发送一些测试事件到不同事件ID
    test_events = [
        (0xC0, "normal_data_1"),
        (0xC1, "normal_data_2"),
        (0xC0, "ERROR_CONDITION"),
        (0xC2, "log_message_1"),
        (0xC1, "normal_data_3")
    ]
    
    print("\n发送测试事件到C++事件总线:")
    for event_id, event_data in test_events:
        bridge.emit_cpp_event(event_id, event_data)
        await asyncio.sleep(0.2)  # 短暂延迟
    
    # 直接通过HookHub发送事件
    print("\n直接通过HookHub发送事件:")
    for i in range(3):
        bridge.hook_hub.emit("data_event", payload=f"direct_event_{i}")
        await asyncio.sleep(0.1)
    
    # 异步发送事件
    print("\n异步发送事件:")
    async_results = await asyncio.gather(
        bridge.hook_hub.emit_async("data_event", payload="async_event_1"),
        bridge.hook_hub.emit_async("data_event", payload="async_event_2"),
        return_exceptions=True
    )
    
    print(f"异步处理结果: {async_results}")
    
    # 模拟应用运行
    print("\n模拟应用运行中... (3秒后退出)")
    await asyncio.sleep(3)
    
    # 清理资源
    print("关闭桥接器...")
    bridge.shutdown()
    print(f"总共处理了 {processor.processed_count} 个事件")


def sync_main():
    """同步主函数"""
    # 在新的事件循环中运行异步主函数
    asyncio.run(async_main())


if __name__ == "__main__":
    sync_main()